package encription;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class Encryptor {
    public static String encrypt(String key, String initVector, String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());

            String s = Base64.encodeBase64String(encrypted);
            System.out.println("encrypted string: "
                    + s+" ,lentgh: "+ s.length() +" byte length: "+ encrypted.length);

            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static String decrypt(String key, String initVector, String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String key = "Bar12345Bar12345"; // 128 bit key
        String initVector = "RandomInitVector"; // 16 bytes IV

        System.out.println(decrypt(key, initVector,
                encrypt(key, initVector, "Hello World")));


       encrypt(key,initVector, "abcd");
       encrypt(key,initVector, "abcdefghijklmnopqrstuvwxyz");
       encrypt(key,initVector, "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz");
       encrypt(key,initVector, "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz");
       encrypt(key,initVector, "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz");



       // AES ECB模式

       // 证件类型  证件号 姓名
       //证件类型枚举类


        //密钥如何存放   网关需要离线解析,则要有密钥和初始向量.
        // 1. 网关本地存储  2.网关请求密码服务器获取. 3.
        //密钥泄露 更改密钥的风险  密钥更改 userId会变    应对措施: 1.批量解密数据,重新加密数据 X
        //

        // 每家医院不一样: 统一userId就比较难实现  密钥和初始向量存储数据库, 每家医院单独一套. 加密解密必须和医院相关.


        //







    }


}